import threading
import queue
import time
import _thread

class TasksQueue:

    # 创建一个线程锁
    lock = threading.Lock()

    # 创建事件对象
    ctsToken = threading.Event()

    #队列和容器
    taskQueue = queue.Queue()

    taskStorage = []
    taskRunning = []

    #构造函数
    def __init__(self):
        pass

    #获取任务队列信号(暂停和恢复)
    def getCtsToken(self):
        return self.ctsToken


    #任务队列数量
    def task_queue_count(self):
        return self.taskQueue.qsize()

    #获取任务数量
    def get_task_count(self):
        return len(self.taskStorage)

    #根据名称获取任务
    def get(self,name):

        tasksResult = list(filter(lambda x: x.get_name() == name, self.taskStorage))
        if len(tasksResult) == 0: return None

        return tasksResult[0]

    #判断任务是否存在
    def is_exists(self,name):
        tasksResult = list(filter(lambda x: x.get_name() == name, self.taskStorage))
        if len(tasksResult) == 0 : return False
        return True

    #任务入列
    def put(self,task):
        if task is None:
            pass
        # 获取锁
        with self.lock:
            self.taskQueue.put(task)
            self.taskStorage.append(task)

    #任务出列
    def pull(self):
        with self.lock:
            try:
                if self.taskQueue.empty():
                    return None
                return  self.taskQueue.get()
            except Exception as ex:
                return None

    #暂停
    def paused(self):
        self.threadToken.clear()

    #恢复
    def resumed(self):
        self.threadToken.set()

    def execute(self):
        _thread.start_new_thread(self.worker,())

    def worker(self):
        while True:
            try:

                time.sleep(0.05)

                if self.ctsToken.is_set():
                    self.ctsToken.wait()  # 等待事件被设置

                task = self.pull()

                if task is  None:
                    continue
                print('---->')
                print(task)

                self.taskRunning.append(task)
                _thread.start_new_thread(self.executeTask, (task,))

            except Exception as ex:
                print('发生错误：')
                print(ex)

    def executeTask(self,task):
        try:
            task.handler()
        except Exception as ex:
            print('发生错误。。。')
            print(ex)

        print('---->结束了')

        self.execute_finish(task)

    #移除任务
    def execute_finish(self,task):
        try:
            self.taskStorage.remove(task)
            self.taskRunning.remove(task)
        except Exception as ex:
            print('xccc')
